package com.example.pageexample.view;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.pageexample.R;
import com.example.pageexample.base.BaseAdapter;
import com.example.pageexample.database.Picture;

/**
 * 图片列表的Adapter
 * @author mailanglideguozhe
 * @date 20210613
 */
public class PictureAdapter extends BaseAdapter<Picture> {
    private static final String TAG = "PictureAdapter";
    //列表View的长宽系数，即高度/宽度
    private float mRatio = 1.00f;
    @Override
    public void setViewData(ViewHolder holder, int pos, Picture picture) {
        if(null != picture){
            //实例化图片显示
            View view = holder.itemView;
            ImageView imageView = holder.imageView;
            ViewGroup.LayoutParams lp = imageView.getLayoutParams();
            Glide.with(view.getContext()).asBitmap().load(picture.url).placeholder(R.drawable.abc_vector_test).override(lp.width, lp.height).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition transition) {
                    //根据bitmap的长宽比例，调整view的高度
                    mRatio = bitmap.getHeight()* 1.00f / bitmap.getWidth();
                    if(mRatio > 1.5f){
                        mRatio = 1.5f;
                    }else if(mRatio < 0.5f){
                        mRatio = 0.5f;
                    }
                    Log.d(TAG, "mRatio = "+mRatio+",height = "+bitmap.getHeight()+",width = "+bitmap.getWidth());
                    lp.width = lp.width;
                    lp.height = (int)(lp.width * mRatio);
                    imageView.setLayoutParams(lp);
                    holder.itemView.requestLayout();
                    imageView.setImageBitmap(bitmap);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                }
            });
        }
    }

    /**
     * 设置布局id
     * @return
     */
    @Override
    public int getLayoutId() {
        return R.layout.item_picture;
    }
}
